<?php
namespace app\api\controller\deerhome\user;

use app\api\controller\deerhome\user\BaseAuth;
use think\Db;
use think\Log;
use think\Validate;

/**
 * 服务订单支付
 */
class Pay extends BaseAuth
{
    //微信拉起支付
    public function weixin_jsapi()
    {
        $id=$this->request->param("id",0,'intval');
        $is_gzh=$this->request->param("is_gzh",0,'intval');
        $data=Db::name("deerhome_order")->where("id",$id)->where("jz_user_id",$this->_user['id'])->find();
        if(!$data){
            $this->err("订单不存在");
        }
        if($data['status']>5){
            $this->err("该订单状态不可支付");
        }
        $need_pay=bcsub($data['price_need_pay'],$data['price_payed'],2);
        if($need_pay<=0){
            $this->err("该订单无需支付");
        }
        //查找子单号
        $sub_order=Db::name("deerhome_order_pay_log")->where("order_sn",$data['sn'])->where("status",1)->find();
        if(!$sub_order){
            $this->err("待支付的订单不存在");
        }
        $need_pay=(int)bcmul($need_pay,100,0);
        $order_sn=$sub_order['order_sn']."S".$sub_order['id'];
        $openid=$is_gzh==1?$this->_user['wxid_gzh']:$this->_user['wxid'];
        $options=[];
        try{
            $config=$is_gzh==1?$this->getWeixinGzhConfig():$this->getWeixinConfig();
            $payment = \WePayV3\Order::instance($config);
            $options = [
                'appid'             => $config['appid'],
                'mchid'             => $config['mch_id'],
                'description'             => $data['item_name'],
                'out_trade_no'     => $order_sn,
                'notify_url'       => $this->notifyUrlWechat(),
                'amount'       => ['total' => $need_pay, 'currency' => 'CNY'],
                'payer'        => ['openid' => $openid]
            ];
            $options = $payment->create('jsapi',$options,$sub_order['prepay_id']);
            $prepayId=\str_ireplace("prepay_id=","",$options['package']);
            Db::name("deerhome_order_pay_log")->where("id",$sub_order['id'])->update(['prepay_id'=>$prepayId]);
        }catch(\Exception $e){
            Log::error('【微信支付拉起失败】'
            .$order_sn
            .'=>'
            .$e->getMessage()
            ."\n"
            .json_encode($options,JSON_UNESCAPED_UNICODE));
            $this->err($e->getMessage());
        }
        $this->ok($options);
   }
  
   /**
    * 储值卡支付
   */
   public function wallet()
   {
        $id=$this->request->param("id",0,'intval');
        $data=Db::name("deerhome_order")->where("id",$id)->where("jz_user_id",$this->_user['id'])->find();
        if(!$data){
            $this->err("订单不存在");
        }
        if($data['status']>5){
            $this->err("该订单状态不可支付");
        }
        $need_pay=bcsub($data['price_need_pay'],$data['price_payed'],2);
        if($need_pay<=0){
            $this->err("该订单无需支付");
        }
        //查找子单号
        $sub_order=Db::name("deerhome_order_pay_log")->where("order_sn",$data['sn'])->where("status",1)->find();
        if(!$sub_order){
            $this->err("待支付的订单不存在",1);
        }
        $need_pay=$sub_order['price'];
        if(bccomp($this->_user['wallet_charge'],$need_pay,2)==-1){
            $this->err("储值卡余额不足",1);
        }
        $wallet_left=bcsub($this->_user['wallet_charge'],$need_pay,2);
        //更新订单信息
        $upateOrder=[];
        $upateOrder['price_payed']=bcadd($data['price_payed'],$need_pay,2);
        //订单日志
        $orderLog=[
            'order_id'=>$data['id'],
            'add_time'=>date("Y-m-d H:i:s"),
            'ac_user'=>'用户',
            'note'=>"补差价￥{$need_pay}元，支付成功"
        ];
        if($data['price_payed']==0){
            $upateOrder['status']=2;
            $orderLog['note']="支付成功，等待派单";
            if($data['order_type']==1 && $data['order_way']==2){
                $upateOrder['status']=3;
                $orderLog['note']="支付成功，等待到店服务";
            }
        }
        //支付流水日志
        $payLog=[
            'order_sn'=>$data['sn'],
            'price'=>$need_pay*-1,
            'pay_time'=>date("Y-m-d H:i:s"),
            'status'=>2,
            'is_wallet'=>1,
            'payway_type'=>1,
            'pay_way'=>"储值卡支付",
            'note'=>"订单{$data['sn']}"
        ];

        //更新分佣
        if($data['agent_lev1_percent']>0){
            $upateOrder['agent_lev1_price']=bcdiv(bcmul($data['price_need_pay'],$data['agent_lev1_percent'],2),100,2);
        }
        if($data['agent_lev2_percent']>0){
            $upateOrder['agent_lev2_price']=bcdiv(bcmul($data['price_need_pay'],$data['agent_lev2_percent'],2),100,2);
        }

        Db::startTrans();
        try{
            Db::name("deerhome_order")->where("id",$data['id'])->update($upateOrder);
            Db::name("deerhome_order_log")->insert($orderLog);
            Db::name("deerhome_order_pay_log")->where("id",$sub_order['id'])->update($payLog);
            Db::name("deerhome_user")->where("id",$data['jz_user_id'])->update([
                "wallet_charge"=>$wallet_left
            ]);
            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            $this->err($e->getMessage(),1);
        }
        $this->ok();
   }

}
